import { createHash } from 'crypto';

// utility function for using crypto library
export function getMD5Hash(str: string): string {
	const md5 = createHash('md5');
	md5.update(str);
	return md5.digest('hex');
}

/**
 * 搜索第一个匹配的子buffer
 * @param buffer 被搜索的buffer
 * @param subBuffer 需要搜索的buffer
 * @return -1 为搜索到，ret>0 搜索到的位置
 */
export function findBuffer(buffer: Buffer, subBuffer: Buffer): number {
	for (let n = 0; n <= buffer.byteLength - subBuffer.byteLength; n++) {
		let match = true;
		for (let m = 0; m < subBuffer.byteLength; m++) {
			if(buffer[n+m] !== subBuffer[m]){
				match = false;
				break;
			} 
		}
		if(match) return n;
	}
	return -1;
}

export function printBuffer(buffer:Buffer){
	console.log(`${buffer.toString('hex')}`);
}